package minicat.coyote.components;

import java.io.IOException;
import java.io.InputStream;

/**
 * 把请求信息封装为Request对象（根据InputSteam输入流封装）
 */
public class Request {

    private static final String root = "ROOT/index.html";
    private String method; // 请求方式，比如GET/POST
    private String host;
    private int port;
    private String path;
    private String url;  // 例如 /,/index.html

    private InputStream inputStream;  // 输入流，其他属性从输入流中解析出来


    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public Request() {
    }


    // 构造器，输入流传入
    public Request(InputStream inputStream) throws IOException {
        this.inputStream = inputStream;

        // 从输入流中获取请求信息
        int count = 0;
        while (count == 0) {
            count = inputStream.available();
        }

        byte[] bytes = new byte[count];
        inputStream.read(bytes);

        String inputStr = new String(bytes);
        /*
        GET /demo/index.html HTTP/1.1
        Host: localhost:9090
        * */
        String urlStr = inputStr.split("\\n")[0];  // GET / HTTP/1.1
        String[] strings = urlStr.split(" ");
        this.method = strings[0];
        this.url = strings[1];
        if(this.url.equals("/")){
            this.url = this.url + root;
        }
        this.path = "/"+this.url.split("/")[1];
        String hostStr = inputStr.split("\\n")[1];
        this.host = hostStr.split(":")[1].trim();
        this.port = Integer.parseInt(hostStr.split(":")[2].trim());

        System.out.println("=====>>method:" + method);
        System.out.println("=====>>url:" + url);

    }
}
